package rj.cometome;

import android.util.Log;

public class ArrowLoop {
	private final static int RATE = 30;
	private final static int UPDATE_TIME = 1000000000 / RATE;
	
	Arrow m_arrow;
	boolean running = false;
	boolean paused = false;
	int fps = 60;
	int frameCount = 0;
	
	public ArrowLoop(Arrow arr) {
		m_arrow = arr;
	}
	
	public void startLoop() {
		running = true;
		runLoop();
	}
	
	public void runLoop() {
		double lastUpdateTime = System.nanoTime();
		int lastSecondTime = (int)(lastUpdateTime / 1000000000);
		
		while(running) {
			double currentTime = System.nanoTime();
			
			if (!paused) {
				while(currentTime - lastUpdateTime > UPDATE_TIME) {
					m_arrow.update();
					frameCount++;
					lastUpdateTime += UPDATE_TIME;
				}
				if (currentTime - lastUpdateTime > UPDATE_TIME) {
					lastUpdateTime = currentTime - UPDATE_TIME;
				}
				
				int thisSecond = (int)(lastUpdateTime / 1000000000);
				if (thisSecond > lastSecondTime) {
					fps = frameCount;
					frameCount = 0;
					lastSecondTime = thisSecond;
				}
			
				while(currentTime - lastUpdateTime < UPDATE_TIME) {
					Thread.yield();
					try {
						Thread.sleep(1);
					}
					catch(Exception e) {
					}
					currentTime = System.nanoTime();
				}
				
			}
		}
	}
}
